<template>
  <el-row class="rowNavStyle">
    <el-col :span="24" class="colNavStyle">
      <menuButton
        @addUserKey="addClick"
        @closeUserKey="batchCloseClick"
        @enableUserKey="batchEnableClick"
        helper-path="pages/f8565f"
      ></menuButton>
    </el-col>
  </el-row>
  <el-table
    :data="tableData"
    stripe
    :border="true"
    row-key="userId"
    @selection-change="SelectionChange"
    v-loading="loading"
    :scroll-x="true"
    ref="userRef"
    :fit="true"
    style="width: 100%"
  >
    <el-table-column type="selection" width="55" />
    <!-- 动态列 -->
    <el-table-column
      show-overflow-tooltip
      v-for="itme in columns"
      :key="itme.fieldEnName"
      :prop="itme.fieldEnName"
      :label="itme.fieldCnName"
      :min-width="itme.fieldWidth"
      :sortable="itme.fieldSortable"
      :align="itme.fieldAlign"
    >
      <template v-if="itme.fieldSlot === 'sexSlot'" #default="sexSlot">
        <el-tag v-if="sexSlot.row.sex == 1" type="primary">男</el-tag>
        <el-tag v-if="sexSlot.row.sex == 2" type="danger">女</el-tag>
      </template>
      <template v-else-if="itme.fieldSlot === 'isOpen'" #default="isOpen">
        <el-switch
          :before-change="switchClick"
          v-model="isOpen.row.isOpen"
          class="ml-2"
          inline-prompt
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          active-text="开启中"
          inactive-text="关闭中"
        />
      </template>
    </el-table-column>

    <el-table-column fixed="right" label="操作" align="center" width="230">
      <template #default="scope">
        <dataRowButton
          :v-loading="dataRowLoading"
          :model="scope.row"
          @editUserKey="handleEdit(scope.row)"
          @setUserRoleKey="setUserRoleClick(scope.row)"
        ></dataRowButton>
      </template>
    </el-table-column>
  </el-table>
  <addOrEdit
    :isVisibles="isVisibles"
    :modelData="userModel"
    :dialogTitle="dialogTitle"
    @closeBnt="colosDialog"
  ></addOrEdit>
  <setUserRole
    :isVisibles="isDrawerVisibles"
    :modelData="userModel"
    :dialogTitle="dDrawerTitle"
    @closeBnt="colosDrawerClick"
  ></setUserRole>
</template>

  <script lang="ts" setup>
import { getUser, setUserIsOpen } from "@/api/user";
import addOrEdit from "../user/addOrEdit.vue";
import { UpdateIsOpenInPut } from "@/model/public/public";
import { ElMessage, ElMessageBox } from "element-plus";
import {  onMounted, reactive, ref } from "vue";
import { SysUser, SysUserOutPut } from "../../model/user/user";
import setUserRole from "../user/setUserRole.vue";
import menuButton from "@/components/menuButton.vue";
import dataRowButton from "@/components/dataRowButton.vue";
import { GetMenuColsByMenuId } from "@/api/publicTool";
//初始加载
onMounted(() => {
  // getUserMsg();
  GetMenuColsByMenuIdMsg();
});
const userRef = ref();
const loading = ref(true);
const dataRowLoading = ref(true);
//table数据
const tableData = ref<SysUserOutPut[]>([]);
//控制弹出层显隐
const isVisibles = ref<boolean>(false);
//弹出层标题
const dialogTitle = ref<string>();
//控制抽屉显隐
const isDrawerVisibles = ref<boolean>(false);
//抽屉标题
const dDrawerTitle = ref<string>();
//人员模型数据
const userModel = reactive<SysUser>({
  UserId: "",
  CorporationKey: "",
  Age: 0,
  Sex: "1",
  DepartmentId: "",
  UserName: "",
  Password: "",
  IsOpen: true,
});

//设置用户是否启用输入模型
const updateUserIsOpenInPut = reactive<UpdateIsOpenInPut>({
  Keys: [],
  IsOpen: false,
});

// 选中项
const selectedRows = ref<SysUserOutPut[]>([]);
//定义列
const columns = ref();
//菜单列
const GetMenuColsByMenuIdMsg = async () => {
  columns.value = await GetMenuColsByMenuId();
  if (columns.value.length > 1) {
    getUserMsg();
  } else {
    columns.value = [];
  }
};

//获取table数据
const getUserMsg = () => {
  getUser({ departmentId: "" })
    .then(({ data }) => {
      tableData.value = data;
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

//复选框事件
const SelectionChange = (val: SysUserOutPut[]) => {
  selectedRows.value = val;
};

//关闭弹出层
const colosDialog = function () {
  getUserMsg();
  isVisibles.value = false;
};

//关闭抽屉
const colosDrawerClick = function () {
  isDrawerVisibles.value = false;
};

//设置用户角色事件
const setUserRoleClick = function (model: SysUserOutPut) {
  if (model.corporationKey === "" || model.corporationKey === undefined) {
    ElMessage({
      message: "公司不能为空",
      type: "warning",
    });
    return;
  }

  dDrawerTitle.value = "设置用户【" + model.userName + "】的角色";
  isDrawerVisibles.value = true;
  userModel.CorporationKey = model.corporationKey;
  userModel.UserId = model.userId;
};

//新增
const addClick = function () {
  const model = ref<SysUserOutPut[]>([]);
  addOrEditMethod(model.value[0], true);
};
//行内编辑事件
const handleEdit = function (model: SysUserOutPut) {
  dataRowLoading.value = false;
  addOrEditMethod(model, false);
};

//新增或编辑方法
const addOrEditMethod = function (model: SysUserOutPut, isAdd: boolean) {
  if (isAdd) {
    userModel.UserId = "";
    userModel.CorporationKey = "";
    userModel.Age = 0;
    userModel.Sex = "1";
    (userModel.DepartmentId = ""),
      (userModel.UserName = ""),
      (userModel.Password = ""),
      (userModel.IsOpen = true);
  } else {
    userModel.UserId = model.userId;
    userModel.CorporationKey = model.corporationKey;
    userModel.Age = model.age;
    userModel.Sex = model.sex.toString();
    (userModel.DepartmentId = model.departmentId),
      (userModel.UserName = model.userName),
      (userModel.Password = model.password),
      (userModel.IsOpen = model.isOpen);
  }
  dialogTitle.value = isAdd ? "新增用户" : "编辑用户";
  isVisibles.value = true;
};

//批量关闭
const batchCloseClick = function () {
  if (selectedRows.value.length == 0) {
    ElMessage({
      message: "请选择一条数据进行操作",
      type: "warning",
    });
  } else {
    setIsOpen(false);
    updateUserIsOpenInPut.Keys = selectedRows.value.map((f) => f.userId);
    updateUserIsOpenInPut.IsOpen = false;
  }
};

//批量启用
const batchEnableClick = function () {
  if (selectedRows.value.length == 0) {
    ElMessage({
      message: "请选择一条数据进行操作",
      type: "warning",
    });
  } else {
    setIsOpen(true);
    updateUserIsOpenInPut.Keys = selectedRows.value.map((f) => f.userId);
    updateUserIsOpenInPut.IsOpen = true;
  }
};
//设置用户启用状态
const setIsOpen = function (isOpen: boolean) {
  var title = isOpen
    ? "你确认要开启选中用户，开启后用户将可以使用？"
    : "你确认要关闭选中用户，关闭后用户将停用！";
  ElMessageBox.confirm(title, "提示消息", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      setUserIsOpen(updateUserIsOpenInPut).then(({ data, code, msg }) => {
        if (code == 200) {
          getUserMsg();
          ElMessage({
            message: msg,
            type: "success",
          });
        }
      });
    })
    .catch(() => {
      //取消
    });
};

//禁止点页面的滑块
const switchClick = function () {
  return new Promise((_, reject) => {
    return reject(new Error("Error"));
  });
};
</script>
  <style scoped>
.rowStyle {
  border: 1px solid #00152914;
  box-shadow: 0 1px 4px #00152914;
  margin-bottom: 3px;
}
.colStyle {
  height: 50px;
  display: flex;
  justify-content: left;
  align-items: center;
  padding-left: 5px;
}

/* .el-table {
  display: table-cell !important;
} */
</style>